const { sys_config_model: SysConfigModel } = require('../models');
const DateUtils = require('../utils/dateUtils');
const { Op } = require('sequelize');
const { realDelete } = require('../config/system');

class ConfigService {
    /**
     * 创建系统配置
     * @param {Object} configData 配置数据
     */
    async createConfig(configData) {
        return await SysConfigModel.create({
            ...configData,
            is_deleted: 0,
            create_time: DateUtils.getCurrentTime(),
            update_time: DateUtils.getCurrentTime()
        });
    }

    /**
     * 更新系统配置
     * @param {number} id 配置ID
     * @param {Object} configData 配置数据
     */
    async updateConfig(id, configData) {
        const existingConfig = await SysConfigModel.findOne({
            where: { id }
        });
        if (!existingConfig) {
            throw new Error('配置数据不存在');
        }

        await existingConfig.update({
            ...configData,
            update_time: DateUtils.getCurrentTime()
        });

        return existingConfig;
    }

    /**
     * 删除系统配置
     * @param {number} id 配置ID
     */
    async deleteConfig(id) {
        const config = await SysConfigModel.findByPk(id);
        if (!config) {
            throw new Error('配置数据不存在');
        }
        if (realDelete) {
            // 真实删除
            await config.destroy();
        } else {
            // 软删除
            await config.update({
                is_deleted: 1,
                update_time: DateUtils.getCurrentTime()
            });
        }
    }

    /**
     * 获取系统配置详情
     * @param {number} id 配置ID
     */
    async getConfigById(id) {
        return await SysConfigModel.findOne({
            where: { id, is_deleted: 0 }
        });
    }

    /**
     * 获取系统配置列表
     * @param {Object} query 查询条件
     */
    async getConfigList(query) {
        const { config_name, config_key, pageNum = 1, pageSize = 10 } = query;
        const where = { is_deleted: 0 };

        if (config_name) {
            where.config_name = { [Op.like]: `%${config_name}%` };
        }
        if (config_key) {
            where.config_key = { [Op.like]: `%${config_key}%` };
        }

        return await SysConfigModel.findAndCountAll({
            where,
            offset: (pageNum - 1) * pageSize,
            limit: parseInt(pageSize),
            order: [['create_time', 'DESC']]
        });
    }

    /**
     * 获取所有系统配置
     * @param {Object} query 查询条件
     */
    async getAllConfig(query = {}) {
        const { config_name, config_key } = query;
        const where = { is_deleted: 0 };

        if (config_name) {
            where.config_name = { [Op.like]: `%${config_name}%` };
        }
        if (config_key) {
            where.config_key = { [Op.like]: `%${config_key}%` };
        }

        return await SysConfigModel.findAll({
            where,
            order: [['create_time', 'DESC']]
        });
    }
}

module.exports = new ConfigService();